import { defineStore } from 'pinia'
import {
  getFirstCategory,
  getSecondCategory,
  getThirdCategory,
} from '@/api/category'
import {
  getAttributes,
  addAttributes,
  updateAttributes,
  deleteAttrbites,
} from '@/api/attribute'
import { CategoryState } from './types/type'
import type { Attrbiute } from '@/api/attribute/type'
import { reactive } from 'vue'
import { Message } from '@/utils/message'

const categoryStore = defineStore('category', {
  state: (): CategoryState => {
    return {
      category1: [],
      c1Id: undefined,
      c2Id: undefined,
      c3Id: undefined,
      category2: [],
      category3: [],
      attributes: [],
      attributeInfo: reactive<Attrbiute>({
        name: '',
        value: [],
        cid: undefined,
      }),
      attributeValue: [],
    }
  },
  actions: {
    async getCategory1() {
      const result = await getFirstCategory()
      if (result.code === 200) {
        this.category1 = result.data
        return Promise.resolve(result.ok)
      }
    },
    async getCategory2() {
      const result = await getSecondCategory(this.c1Id!)
      if (result.code === 200) {
        this.category2 = result.data
        return Promise.resolve(result.ok)
      }
    },
    async getCategory3() {
      const result = await getThirdCategory(this.c2Id!)
      if (result.code === 200) {
        this.category3 = result.data
        return Promise.resolve(result.ok)
      }
    },
    async getCateAttributes() {
      const result = await getAttributes(this.c3Id!)
      if (result.code === 200) {
        this.attributes = result.data
        return Promise.resolve(result.ok)
      }
    },
    async saveAttribute() {
      this.attributeInfo.cid = this.c3Id
      if (this.attributeValue.length === 0) {
        return Message('error', '请至少输入一个属性值', 2000)
      }
      let result
      this.attributeInfo.value = []
      this.attributeValue.forEach((item) => {
        if (item.value.trim().length > 0) {
          this.attributeInfo.value.push(item.value)
        }
      })
      if (this.attributeInfo.id) {
        result = await updateAttributes(this.attributeInfo)
      } else {
        result = await addAttributes(this.attributeInfo)
      }
      if (result.code === 200) {
        this.getCateAttributes()
        this.attributeValue = []
        this.attributeInfo.value = []
        this.attributeInfo.name = ''
        Message('success', result.message, 2000)
        return Promise.resolve(result.ok)
      }
    },
    async deleteAttribute(id: number) {
      const result = await deleteAttrbites(id)
      if (result.code === 200) {
        this.getCateAttributes()
        Message('success', result.message, 2000)
      }
    },
  },
  getters: {},
})

export default categoryStore
